package com.chunxuan.langquan.ui.activity.live;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chunxuan.langquan.R;
import com.m7.imkfsdk.utils.ToastUtils;
import com.tencent.rtmp.ITXLivePushListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePushConfig;
import com.tencent.rtmp.TXLivePusher;
import com.tencent.rtmp.ui.TXCloudVideoView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class PushLiveActivity extends AppCompatActivity {

    Button btStart;
    TXCloudVideoView mPusherView;
    TXLivePusher mLivePusher;
    ImageView ivBack;
    ImageView ivBg;
    private boolean mIsPushing = false;
    TXLivePushConfig mLivePushConfig;
    TextView tvLiveUrl;

    private int mVideoResolution = TXLiveConstants.VIDEO_RESOLUTION_TYPE_540_960;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, PushLiveActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.live_activity_push_live);
        ivBack = findViewById(R.id.iv_back);
        tvLiveUrl = findViewById(R.id.tv_live_url);
        mPusherView = (TXCloudVideoView) findViewById(R.id.pusher_tx_cloud_view);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvLiveUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipData clipData = ClipData.newPlainText("text", tvLiveUrl.getText().toString());
                ClipboardManager mClipboardManager =
                        (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                mClipboardManager.setPrimaryClip(clipData);
                Toast.makeText(PushLiveActivity.this, "直播地址已复制", Toast.LENGTH_SHORT).show();
            }
        });
        ivBg = findViewById(R.id.iv);
        btStart = findViewById(R.id.livepusher_btn_start);
//        //启动本地摄像头预览
//        mPusherView = (TXCloudVideoView) findViewById(R.id.pusher_tx_cloud_view);
        if (checkPublishPermission()) {
            initListener();
            initTXLivePusher();
        }
    }

    public void initListener() {
        btStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePush();
            }
        });
    }

    private void togglePush() {

        if (mIsPushing) {
            stopPush();
        } else {
//            startPush();
            fetchPusherURL();
        }
    }

    private void stopPush() {
        Log.e("stopPush", "=====");
        if (!mIsPushing) {
            return;
        }
        if (mLivePusher == null) {
            return;
        }
        // 停止本地预览
        mLivePusher.stopCameraPreview(true);
        // 移除监听
        mLivePusher.setPushListener(null);
        // 停止推流
        mLivePusher.stopPusher();
        // 隐藏本地预览的View
        mPusherView.setVisibility(View.GONE);
        ivBg.setVisibility(View.VISIBLE);
        mIsPushing = false;
        btStart.setBackgroundResource(R.drawable.live_icon_livepusher_start);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopPush();
        if (mPusherView != null) {

            mPusherView.onDestroy();
        }
    }

    public void initTXLivePusher() {
        mLivePushConfig = new TXLivePushConfig();
        mLivePusher = new TXLivePusher(this);
        // 一般情况下不需要修改 config 的默认配置
        mLivePusher.setConfig(mLivePushConfig);
        mLivePusher.startCameraPreview(mPusherView);
    }

    public void startPush(String url) {
        // rtmp 推流地址
//        String rtmpURL = "rtmp://132711.livepush.myqcloud" +
//                ".com/live/teacher?txSecret=6b775c689f6737ef81e0cfe9345cb40a&txTime=605A9645";

//        String rtmpURL = "rtmp://3891.livepush.myqcloud" +
//                ".com/live/3891_user_74b85faf_85ae?bizid=3891&txSecret" +
//                "=d64637e95588b53fa4686499c6c90307&txTime=6045BB92";
        mPusherView.setVisibility(View.VISIBLE);
        // 播放回调
        mLivePusher.setPushListener(new ITXLivePushListener() {
            @Override
            public void onPushEvent(int event, Bundle bundle) {
                if (event == TXLiveConstants.PUSH_ERR_NET_DISCONNECT
                        || event == TXLiveConstants.PUSH_ERR_INVALID_ADDRESS
                        || event == TXLiveConstants.PUSH_ERR_OPEN_CAMERA_FAIL
                        || event == TXLiveConstants.PUSH_ERR_OPEN_MIC_FAIL) {
                    // 遇到以上错误，则停止推流
                    stopPush();
                }
            }

            @Override
            public void onNetStatus(Bundle bundle) {

            }
        });
        // 添加后台垫片推流参数
        Bitmap bitmap = decodeResource(getResources(), R.drawable.livepusher_pause_publish);
        mLivePushConfig.setPauseImg(bitmap);
        mLivePushConfig.setPauseImg(300, 5);
        // 设置暂停时，只停止画面采集，不停止声音采集。
        mLivePushConfig.setPauseFlag(TXLiveConstants.PAUSE_FLAG_PAUSE_VIDEO);//
        // 设置推流分辨率
        mLivePushConfig.setVideoResolution(mVideoResolution);
        mLivePusher.setConfig(mLivePushConfig);
        mLivePusher.startCameraPreview(mPusherView);
        int resultCode = mLivePusher.startPusher(url.trim());
        mIsPushing = true;
        onPushStart(resultCode);
        Log.e("resultCode", "开启直播：" + resultCode);

    }

    private void onPushStart(int code) {
        switch (code) {
            case Constants.PLAY_STATUS_SUCCESS:
                ivBg.setVisibility(View.GONE);
                btStart.setBackgroundResource(R.drawable.live_icon_livepusher_pause);
                break;
            case Constants.PLAY_STATUS_LICENSE_ERROR:

            default:
                ToastUtils.showShort(this, "开启直播失败");
                break;
        }
    }

    /**
     * 获取资源图片
     *
     * @param resources
     * @param id
     * @return
     */
    private Bitmap decodeResource(Resources resources, int id) {
        TypedValue value = new TypedValue();
        resources.openRawResource(id, value);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inTargetDensity = value.density;
        return BitmapFactory.decodeResource(resources, id, opts);
    }


    private void fetchPusherURL() {

        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(Constants.URL_FETCH_PUSH_URL)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ToastUtils.showShort(PushLiveActivity.this, "获取直播地址失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        JSONObject jsonRsp = new JSONObject(response.body().string());
                        final String pusherURLDefault = jsonRsp.optString(Constants.URL_PUSH);
                        String rtmpPlayURL = jsonRsp.optString(Constants.URL_PLAY_RTMP);
                        final String flvPlayURL = jsonRsp.optString(Constants.URL_PLAY_FLV);
                        String hlsPlayURL = jsonRsp.optString(Constants.URL_PLAY_HLS);
                        String realtimePlayURL = jsonRsp.optString(Constants.URL_PLAY_ACC);
                        Log.e("pushurl", "pushurl" + pusherURLDefault);
                        Log.e("flv", "fliv:" + flvPlayURL);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvLiveUrl.setText(flvPlayURL);
                                startPush(pusherURLDefault);
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


    private boolean checkPublishPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE)) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]),
                        2);
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                checkPublishPermission();
                return;
            }
        }
        initListener();
    }
}